from Util.loadSetting import getConfigDict
from Util.DataBase import DataBase
from flask import Flask, request, jsonify

app = Flask(__name__)

config_dict = getConfigDict()
port = config_dict['PORT']
api_key = config_dict['API_KEY']
db = DataBase()
if not 'k' in db.get_schema():
    db.create_table('k', {'v': 'TEXT'})
cache_set = {i[0] for i in db.query('k')}
db.close()


def add(v):
    global cache_set
    db = DataBase()
    try:
        if not 'k' in db.get_schema():
            db.create_table('k', {'v': 'TEXT'})
        if not v:
            v = ''
        if not v in cache_set:
            result = db.insert_dict('k', {'v': str(v)})
            if result:
                cache_set.add(v)
            return result
        return False
    finally:
        db.close()


def query(v):
    global cache_set
    if v in cache_set:
        return True
    return False


def query_all():
    global cache_set
    return list(cache_set)


def delete(v):
    global cache_set
    db = DataBase()
    try:
        if v in cache_set:
            result = db.delete('k', {'v': str(v)}, False)
            if result:
                cache_set.remove(v)
                return True
        return False
    finally:
        db.close()


def delete_all():
    global cache_set
    db = DataBase()
    try:
        db.drop_table('k')
        cache_set.clear()
    finally:
        db.close()


def check_api_key(provided_api_key):
    if provided_api_key != api_key:
        return jsonify({'error': 'Invalid API_KEY'}), 403
    return None


@app.route('/add', methods=['GET'])
def api_add():
    provided_api_key = request.args.get('apikey')
    error_response = check_api_key(provided_api_key)
    if error_response:
        return error_response

    v = request.args.get('v', '')
    result = add(v)
    return jsonify({'success': result})


@app.route('/query', methods=['GET'])
def api_query():
    provided_api_key = request.args.get('apikey')
    error_response = check_api_key(provided_api_key)
    if error_response:
        return error_response

    v = request.args.get('v', '')
    result = query(v)
    return jsonify({'success': result})


@app.route('/query_all', methods=['GET'])
def api_query_all():
    provided_api_key = request.args.get('apikey')
    error_response = check_api_key(provided_api_key)
    if error_response:
        return error_response

    result = query_all()
    return jsonify({'success': result})


@app.route('/delete', methods=['GET'])
def api_delete():
    provided_api_key = request.args.get('apikey')
    error_response = check_api_key(provided_api_key)
    if error_response:
        return error_response

    v = request.args.get('v', '')
    result = delete(v)
    return jsonify({'success': result})


@app.route('/delete_all', methods=['GET'])
def api_delete_all():
    provided_api_key = request.args.get('apikey')
    error_response = check_api_key(provided_api_key)
    if error_response:
        return error_response

    delete_all()
    return jsonify({'success': True})


if __name__ == '__main__':
    app.run('0.0.0.0',port=port)
